<script setup>
import {onMounted, reactive, ref, watch} from 'vue'
import {ElImageViewer, ElMessage, ElMessageBox} from 'element-plus'
import {ArrowDown, ArrowLeft, Calendar, Collection, Message, Search, User, UserFilled} from '@element-plus/icons-vue'
import router from "@/router/index.js";
import http from "@/request/http.js";
import {useRoute} from 'vue-router' // 仅新增这一行引入

const route = useRoute() // 新增：获取当前路由

// 新增：判断菜单是否激活
const isMenuActive = (menuKey) => {
  if (menuKey === 'points' && route.path.startsWith('/userInfo/points')) return true
  if (menuKey === 'level' && route.path.startsWith('/userInfo/level')) return true
  if (menuKey === 'mall' && route.path.startsWith('/userInfo/mall')) return true
  // 主路由下匹配activeTab
  return route.path === '/userInfo' && activeTab.value === menuKey
}

// 状态管理
const activeTab = ref('profile')
const securityTab = ref('password') // 新增：账户安全内部的标签页
const isSendingCode = ref(false)
const countdown = ref(60)
const isCancelLoading = ref(false)
const isLogged = ref(false) //用户登陆状态
const checkInStatus = ref({
  hasCheckedIn: false,          // 是否已签到
  continuousDays: 0,            // 连续签到天数
  checkInLoading: false,        // 签到请求加载中
  monthCheckCount: 0,           // 本月累计签到
  totalCheckCount: 0,           // 总签到次数
  rewardTip: ''                 // 签到奖励提示（如积分、等级）
})

//粉丝管理相关状态
const fansActiveTab = ref('fansList')
const fansList = ref([])
const followingList = ref([])
const fansStatistics = ref({
  totalFans: 0,
  totalFollow: 0
})

//搜索相关状态
const searchKeyword = ref('')

//粉丝数据分析数据
const fansAnalysisData = ref({
  growthTrend: [],
  ageDistribution: []
})

// 消息中心相关状态
const messages = ref([])
const selectedMessages = ref([])
const messageLoading = ref(false)

// 消息分页配置
const messagePage = reactive({
  current: 1,
  size: 10,
  total: 0
})


// 添加获取数据分析的方法
const fetchFansAnalysis = async () => {
  try {
    const response = await http.get('/follow/getFansAnalysis')
    if (response.code === 200) {
      fansAnalysisData.value = response.data
    }
  } catch (error) {
    console.error('获取粉丝分析数据失败:', error)
  }
}

// 分页配置
const fansPage = reactive({
  current: 1,
  size: 10,
  total: 0
})

const followingPage = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单引用
const profileFormRef = ref(null)
const passwordFormRef = ref(null)
const emailFormRef = ref(null)
const cancelFormRef = ref(null)

// 用户信息
const userInfo = reactive({
  userId: '',
  username: '',
  avatar: '',
  briefly: '',
  email: '',
  gender: '',
  createTime: ''//创建时间
})

// 原始用户信息，用于重置
const originalUserInfo = ref({})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 邮箱表单
const emailForm = reactive({
  currentEmail: '',
  newEmail: '',
  verifyCode: ''
})

// 注销账号表单
const cancelForm = reactive({
  reason: '',
  password: '',
  otherReason: '' // 新增：其他原因的具体内容
})

// 性别选项
const genderOptions = [
  {label: '男', value: 'male'},
  {label: '女', value: 'female'},
  {label: '保密', value: 'secret'}
]

// 表单验证规则
const profileRules = {
  username: [
    {required: true, message: '请输入昵称', trigger: 'blur'},
    {min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur'}
  ],
  briefly: [
    {max: 100, message: '简介不能超过100个字符', trigger: 'blur'}
  ],
  gender: [
    {required: true, message: '请选择性别', trigger: 'change'}
  ]
}

const passwordRules = {
  oldPassword: [
    {required: true, message: '请输入原密码', trigger: 'blur'}
  ],
  newPassword: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请确认新密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const emailRules = {
  newEmail: [
    {required: true, message: '请输入新邮箱', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change']}
  ],
  verifyCode: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    {len: 6, message: '验证码长度为6位', trigger: 'blur'}
  ]
}

const cancelRules = {
  password: [
    {required: true, message: '请输入密码确认', trigger: 'blur'}
  ],
  reason: [
    {required: true, message: '请选择注销原因', trigger: 'change'}
  ],
  otherReason: [
    {
      validator: (rule, value, callback) => {
        // 只有当选择了"其他原因"时才需要验证
        if (cancelForm.reason === 'other') {
          if (!value || value.trim() === '') {
            callback(new Error('请填写具体原因'))
          } else if (value.trim().length < 5) {
            callback(new Error('具体原因至少需要5个字符'))
          } else {
            callback()
          }
        } else {
          // 如果不是"其他原因"，直接通过验证
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 页面加载时获取用户信息
onMounted(() => {
  //判断用户登录状态
  let login = sessionStorage.getItem("isLogged")
  isLogged.value = login !== null ? login === "true" : false
  if (!isLogged.value) {
    ElMessage.warning('请先登录')
    router.push('/login').then()
    return // 未登录则不再执行后续数据加载
  }
  fetchUserInfo()
  fetchCheckInStatus()       // 获取签到状态（连续天数、本月/总次数）
})

//获取用户信息
const fetchUserInfo = async () => {
  const response = await http.get('/user/userInfo')
  console.log(response)
  if (response.code === 200) {
    const userData = response.data
    //映射后端字段到前端
    userInfo.userId = userData.userId
    userInfo.username = userData.username
    userInfo.avatar = userData.avatar
    userInfo.briefly = userData.briefly
    userInfo.email = userData.email
    userInfo.gender = userData.gender === 1 ? 'male' : userData.gender === 2 ? 'female' : 'secret'
    emailForm.currentEmail = userInfo.email
    originalUserInfo.value = {...userInfo}
  } else {
    ElMessage.error("获取用户信息失败!")
  }
}

//=======粉丝管理方法=====
const fetchFansStatistics = async () => {
  try {
    const response = await http.get(`/follow/getFansStatistics?userId=${userInfo.userId}`)
    if (response.code === 200) {
      fansStatistics.value = response.data
    }
  } catch (error) {
    console.error('获取粉丝统计失败:', error)
  }
}

const fetchFansList = async () => {
  try {
    const response = await http.get('/follow/getFansList', {
      params: {
        page: fansPage.current,
        size: fansPage.size,
        userId: userInfo.userId
      }
    })
    if (response.code === 200) {
      const data = response.data
      fansList.value = (data.records || []).map(fans => ({
        id: fans.id || 0,
        avatar: fans.avatar || '',
        username: fans.username || '',
        attentionTime: fans.attentionTime || '',
        fansId: fans.fansId || 0,
        isFollowing: fans.isFollowing || false
      }))
      fansPage.total = response.data.total || 0

      // 检查是否已关注每个粉丝
      for (let fans of fansList.value) {
        const checkResponse = await http.get(`/follow/checkFollowing/${fans.fansId}`)
        if (checkResponse.code === 200) {
          fans.isFollowing = checkResponse.data
        }
      }
    }
  } catch (error) {
    console.error('获取粉丝列表失败:', error)
    ElMessage.error("获取粉丝列表失败")
  }
}

const fetchFollowingList = async () => {
  try {
    const response = await http.get('/follow/getFollowingList', {
      params: {
        page: followingPage.current,
        size: followingPage.size
      }
    })
    if (response.code === 200) {
      const data = response.data
      followingList.value = (data.records || []).map(following => ({
        id: following.id || 0,
        avatar: following.avatar || '',
        username: following.username || '',
        attentionTime: following.attentionTime || '',
        authorId: following.authorId || 0
      }))
      followingPage.total = data.total || 0
    }
  } catch (error) {
    console.error('获取关注列表失败:', error)
    ElMessage.error("获取关注列表失败")
  }
}

// 搜索粉丝列表
const searchFansList = async () => {
  try {
    const response = await http.get('/follow/searchFans', {
      params: {
        page: fansPage.current,
        size: fansPage.size,
        userId: userInfo.userId,
        keyword: searchKeyword.value
      }
    })
    if (response.code === 200) {
      const data = response.data
      fansList.value = (data.records || []).map(fans => ({
        id: fans.id || 0,
        avatar: fans.avatar || '',
        username: fans.username || '',
        attentionTime: fans.attentionTime || '',
        fansId: fans.fansId || 0,
        isFollowing: fans.isFollowing || false
      }))
      fansPage.total = data.total || 0

      // 检查是否已关注每个粉丝
      for (let fans of fansList.value) {
        const checkResponse = await http.get(`/follow/checkFollowing/${fans.fansId}`)
        if (checkResponse.code === 200) {
          fans.isFollowing = checkResponse.data
        }
      }
    }
  } catch (error) {
    console.error('搜索粉丝列表失败:', error)
    ElMessage.error("搜索粉丝列表失败")
  }
}

// 搜索关注列表
const searchFollowingList = async () => {
  try {
    const response = await http.get('/follow/searchFollowing', {
      params: {
        page: followingPage.current,
        size: followingPage.size,
        keyword: searchKeyword.value
      }
    })
    if (response.code === 200) {
      const data = response.data
      followingList.value = (data.records || []).map(following => ({
        id: following.id || 0,
        avatar: following.avatar || '',
        username: following.username || '',
        attentionTime: following.attentionTime || '',
        authorId: following.authorId || 0
      }))
      followingPage.total = data.total || 0
    }
  } catch (error) {
    console.error('搜索关注列表失败:', error)
    ElMessage.error("搜索关注列表失败")
  }
}

// 搜索方法
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    // 如果搜索关键词为空，则显示全部列表
    if (fansActiveTab.value === 'fansList') {
      await fetchFansList()
    } else if (fansActiveTab.value === 'followingList') {
      await fetchFollowingList()
    }
    return
  }

  if (fansActiveTab.value === 'fansList') {
    await searchFansList()
  } else if (fansActiveTab.value === 'followingList') {
    await searchFollowingList()
  }
}

// 清空搜索
const handleSearchClear = () => {
  if (searchKeyword.value === '') {
    handleReset()
  }
}

// 重置搜索
const handleReset = () => {
  searchKeyword.value = ''
  if (fansActiveTab.value === 'fansList') {
    fetchFansList()
  } else if (fansActiveTab.value === 'followingList') {
    fetchFollowingList()
  }
}

const toggleFollow = async (targetUserId) => {
  try {
    const response = await http.post('/follow/toggle', {
      authorId: targetUserId
    })
    if (response.code === 200) {
      ElMessage.success(response.data)
      // 刷新相关列表
      if (fansActiveTab.value === 'fansList') {
        if (searchKeyword.value) {
          await searchFansList()
        } else {
          await fetchFansList()
        }
      } else if (fansActiveTab.value === 'followingList') {
        if (searchKeyword.value) {
          await searchFollowingList()
        } else {
          await fetchFollowingList()
        }
      }
      fetchFansStatistics()
    } else {
      ElMessage.error(response.msg || '操作失败')
    }
  } catch (error) {
    console.error('关注操作失败:', error)
    ElMessage.error('操作失败')
  }
}

const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

// 分页处理
const handleFansSizeChange = (size) => {
  fansPage.size = size
  fansPage.current = 1
  if (searchKeyword.value) {
    searchFansList()
  } else {
    fetchFansList()
  }
}

const handleFansCurrentChange = (page) => {
  fansPage.current = page
  if (searchKeyword.value) {
    searchFansList()
  } else {
    fetchFansList()
  }
}

const handleFollowingSizeChange = (size) => {
  followingPage.size = size
  followingPage.current = 1
  if (searchKeyword.value) {
    searchFollowingList()
  } else {
    fetchFollowingList()
  }
}

const handleFollowingCurrentChange = (page) => {
  followingPage.current = page
  if (searchKeyword.value) {
    searchFollowingList()
  } else {
    fetchFollowingList()
  }
}

// 标签页切换处理
const handleTabChange = () => {
  searchKeyword.value = '' // 切换标签时清空搜索关键词
  if (fansActiveTab.value === 'fansList') {
    fetchFansList()
  } else if (fansActiveTab.value === 'followingList') {
    fetchFollowingList()
  } else if (fansActiveTab.value === 'fansAnalysis') {
    fetchFansAnalysis()
  }
}

// 监听账户安全标签激活，确保邮箱数据正确
watch(activeTab, (newTab) => {
  if (newTab === 'security') {
    // 当切换到账户安全标签时，确保邮箱表单数据正确
    emailForm.currentEmail = userInfo.email
  }
})

// 监听粉丝标签页变化
watch(fansActiveTab, (newTab) => {
  handleTabChange()
})

// 监听粉丝管理标签激活
watch(activeTab, (newTab) => {
  if (newTab === 'fans') {
    fetchFansStatistics()
    fetchFansList()
    searchKeyword.value = '' // 重置搜索关键词
  }
})

// ======= 消息中心方法 ======
// 获取系统消息列表
const fetchSystemMessages = async () => {
  try {
    messageLoading.value = true
    const response = await http.get('/message/system', {
      params: {
        page: messagePage.current,
        size: messagePage.size
      }
    })
    if (response.code === 200) {
      const data = response.data
      messages.value = (data.records || []).map(msg => ({
        id: msg.id || 0,
        title: msg.title || '',
        content: msg.content || '',
        createTime: msg.createTime || '',
        isRead: msg.isRead || 0
      }))
      messagePage.total = data.total || 0
    } else {
      ElMessage.error('获取消息失败: ' + response.msg)
    }
  } catch (error) {
    console.error('获取系统消息失败:', error)
    ElMessage.error('获取消息失败')
  } finally {
    messageLoading.value = false
  }
}

// 获取未读消息数量
const fetchUnreadMessageCount = async () => {
  try {
    const response = await http.get('/message/system/unread/count')
    if (response.code === 200) {
      // 可以在这里更新未读消息数量，用于显示小红点等
      console.log('未读消息数量:', response.data)
    }
  } catch (error) {
    console.error('获取未读消息数量失败:', error)
  }
}

// 标记消息为已读
const markAsRead = async (messageId) => {
  try {
    const response = await http.put(`/message/${messageId}/read`)
    if (response.code === 200) {
      ElMessage.success('标记已读成功')
      // 更新本地消息状态
      const message = messages.value.find(msg => msg.id === messageId)
      if (message) {
        message.isRead = 1
      }
      fetchUnreadMessageCount() // 刷新未读数量
    } else {
      ElMessage.error(response.msg || '标记已读失败')
    }
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error('标记已读失败')
  }
}

// 批量标记为已读
const batchMarkAsRead = async () => {
  if (selectedMessages.value.length === 0) {
    ElMessage.warning('请选择要标记的消息')
    return
  }

  try {
    const messageIds = selectedMessages.value.map(msg => msg.id)
    const response = await http.put('/message/batch-read', messageIds)
    if (response.code === 200) {
      ElMessage.success('批量标记已读成功')
      // 更新本地消息状态
      messages.value.forEach(msg => {
        if (messageIds.includes(msg.id)) {
          msg.isRead = 1
        }
      })
      selectedMessages.value = []
      fetchUnreadMessageCount() // 刷新未读数量
    } else {
      ElMessage.error(response.msg || '批量标记已读失败')
    }
  } catch (error) {
    console.error('批量标记已读失败:', error)
    ElMessage.error('批量标记已读失败')
  }
}

// 删除消息
const deleteMessage = async (messageId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条消息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await http.delete(`/message/${messageId}`)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      // 从列表中移除
      const index = messages.value.findIndex(msg => msg.id === messageId)
      if (index !== -1) {
        messages.value.splice(index, 1)
      }
      // 如果当前页没有消息了，且不是第一页，就跳转到上一页
      if (messages.value.length === 0 && messagePage.current > 1) {
        messagePage.current--
        fetchSystemMessages()
      }
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除消息失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除消息
const batchDeleteMessages = async () => {
  if (selectedMessages.value.length === 0) {
    ElMessage.warning('请选择要删除的消息')
    return
  }

  try {
    await ElMessageBox.confirm('确定要删除选中的消息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const messageIds = selectedMessages.value.map(msg => msg.id)
    const response = await http.delete('/message/batch', {data: messageIds})
    if (response.code === 200) {
      ElMessage.success('批量删除成功')
      // 重新加载消息列表
      fetchSystemMessages()
      selectedMessages.value = []
    } else {
      ElMessage.error(response.msg || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 刷新消息
const refreshMessages = () => {
  messagePage.current = 1
  fetchSystemMessages()
  fetchUnreadMessageCount()
}

// 表格选择变化
const handleMessageSelectionChange = (selection) => {
  selectedMessages.value = selection
}

// 消息分页处理
const handleMessageSizeChange = (size) => {
  messagePage.size = size
  messagePage.current = 1
  fetchSystemMessages()
}

const handleMessageCurrentChange = (page) => {
  messagePage.current = page
  fetchSystemMessages()
}

// 监听消息中心标签激活
watch(activeTab, (newTab) => {
  if (newTab === 'messages') {
    fetchSystemMessages()
    fetchUnreadMessageCount()
  }
})

// 获取签到状态
const fetchCheckInStatus = async () => {
  try {
    if (!isLogged.value) {
      ElMessage.warning('请先登录')
      router.push('/login').then()
      return
    }

    const response = await http.get('/points/user/checkIn/status')
    if (response.code === 200) {
      const data = response.data
      console.log('接口返回的签到数据:', data); // 添加这行代码，输出接口返回的数据
      checkInStatus.value.hasCheckedIn = data.hasCheckedIn
      checkInStatus.value.continuousDays = data.continuousDays || 0
      checkInStatus.value.monthCheckCount = data.monthCheckCount || 0
      checkInStatus.value.totalCheckCount = data.totalCheckCount || 0
      checkInStatus.value.rewardTip = data.rewardTip || ''
    } else {
      ElMessage.error("获取签到状态失败：" + response.message)
    }
  } catch (error) {
    console.error("获取签到状态异常:", error)
    ElMessage.error("获取签到状态失败，请刷新页面重试")
  }
}

// 执行签到
const handleCheckIn = async () => {
  if (checkInStatus.value.hasCheckedIn) {
    ElMessage.info(`今日已签到，当前连续${checkInStatus.value.continuousDays}天`)
    return
  }

  checkInStatus.value.checkInLoading = true
  try {
    const response = await http.post('/points/checkIn')
    if (response.code === 200) {
      const data = response.data
      checkInStatus.value.hasCheckedIn = true
      checkInStatus.value.continuousDays = data.continuousDays
      checkInStatus.value.monthCheckCount = data.monthCheckCount
      checkInStatus.value.totalCheckCount = data.totalCheckCount
      checkInStatus.value.rewardTip = data.rewardTip

      ElMessage.success({
        message: `签到成功！<br>连续签到${data.continuousDays}天<br>${data.rewardTip}`,
        dangerouslyUseHTMLString: true
      })

      if ([7, 15, 30, 90].includes(data.continuousDays)) {
        ElMessageBox.success({
          title: '里程碑达成',
          message: `恭喜！连续签到${data.continuousDays}天，获得「坚持不懈」徽章一枚`,
          confirmButtonText: '查看徽章'
        }).then(() => {
          ElMessage.info('徽章功能开发中...')
        })
      }
    } else {
      ElMessage.error("签到失败：" + response.message)
    }
  } catch (error) {
    console.error("签到异常:", error)
    ElMessage.error("签到失败，请检查网络后重试")
  } finally {
    checkInStatus.value.checkInLoading = false
  }
}

//头像查看和上传相关状态
const showAvatarViewer = ref(false)

//点击头像放大查看
const handleAvatarClick = (e) => {
  // 阻止事件冒泡到上传组件
  e.stopPropagation()
  if (userInfo.avatar) {
    showAvatarViewer.value = true
  }
}

//头像上传
const triggerAvatarUpload = () => {
  const input = document.querySelector('.avatar-uploader input[type="file"]')
  if (input) {
    input.click()
  }
}

// 头像上传前校验
const beforeAvatarUpload = (rawFile) => {
  const isJpgOrPng = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
  if (!isJpgOrPng) {
    ElMessage.error('请上传JPG或PNG格式的图片')
    return false
  }

  const isLt2M = rawFile.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB')
    return false
  }
  return true
}

// 处理头像上传
const handleAvatarUpload = async (options) => {
  try {
    console.log('准备上传头像:', options.file)
    const formData = new FormData()
    formData.append('file', options.file)
    //调用后端接口
    const response = await http.post('/file', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    if (response.code === 200) {
      const newAvatarUrl = response.data
      userInfo.avatar = newAvatarUrl
      ElMessage.success("头像上传成功")
      //更新后端用户信息的头像地址
      const updateResponse = await http.put('/user/userInfo', {
        userId: userInfo.userId,
        avatar: newAvatarUrl
      })
      if (updateResponse.code !== 200) {
        ElMessage.warning("头像同步到用户信息失败" + updateResponse.msg)
      }
    } else {
      ElMessage.error("头像上传失败" + response.msg)
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败，请重试')
  }
}

// 保存个人资料
const saveProfile = async () => {
  try {
    await profileFormRef.value.validate()
    //性别映射
    const genderMap = {
      'male': 1,
      'female': 2,
      'secret': 0
    }
    //转换性别字段
    const requestData = {
      ...userInfo,
      gender: genderMap[userInfo.gender]
    }

    const response = await http.put('/user/userInfo', requestData)
    if (response.code === 200) {
      originalUserInfo.value = {...userInfo}
      ElMessage.success("个人资料保存成功!")
    } else {
      ElMessage.error("保存失败" + response.msg)
    }
  } catch (error) {
    console.log("保存失败:", error)
    ElMessage.error("保存失败")
  }
}

// 重置个人资料表单
const resetProfileForm = () => {
  profileFormRef.value.resetFields()
  Object.assign(userInfo, originalUserInfo.value)
}

// 发送验证码
const sendVerifyCode = async () => {
  //校验
  if (!emailForm.newEmail) {
    ElMessage.warning('请先输入新邮箱')
    return
  }

  const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailReg.test(emailForm.newEmail)) {
    ElMessage.warning('请输入正确的邮箱格式')
    return
  }

  //先禁用，防止用户多次点击
  isSendingCode.value = true
  const data = await http.get("/email/getEmailCode?email=" + emailForm.newEmail)
  if (data.code === 200) {
    ElMessage.success("发送成功")
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
        isSendingCode.value = false
        countdown.value = 60
      }
    }, 1000)
  } else {
    isSendingCode.value = false
  }
}

// 修改密码
const changePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    const response = await http.put('/user/password', {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
      confirmPassword: passwordForm.confirmPassword
    })
    if (response.code === 200) {
      ElMessage.success("密码修改成功")
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
      //修改成功要重新登陆
      router.push('/login')
    } else {
      ElMessage.error("密码修改失败" + response.msg)
    }
  } catch (error) {
    console.log("密码修改失败", error)
    ElMessage.error("密码修改失败")
  }
}

// 修改邮箱
const changeEmail = async () => {
  try {
    // 使用正确的验证方式
    const valid = await emailFormRef.value.validate()
    if (!valid) return

    const response = await http.put('/user/email', emailForm)
    if (response.code === 200) {
      // 更新用户信息中的邮箱
      userInfo.email = emailForm.newEmail
      // 更新当前邮箱显示
      emailForm.currentEmail = emailForm.newEmail
      // 修改成功后清空新邮箱和验证码字段
      emailForm.newEmail = ''
      emailForm.verifyCode = ''
      ElMessage.success("邮箱修改成功!")
    } else {
      ElMessage.error(response.msg || "邮箱修改失败")
    }
  } catch (error) {
    console.log("邮箱修改失败", error)
    ElMessage.error("邮箱修改失败")
  }
}

// 确认注销账号
const confirmCancelAccount = async () => {
  try {
    // 如果是其他原因，需要额外检查内容是否填写
    if (cancelForm.reason === 'other' && (!cancelForm.otherReason || cancelForm.otherReason.trim() === '')) {
      ElMessage.error('请填写具体原因')
      return false
    }

    if (cancelForm.reason === 'other' && cancelForm.otherReason.trim().length < 5) {
      ElMessage.error('具体原因至少需要5个字')
      return false
    }

    await cancelFormRef.value.validate()

    ElMessageBox.confirm(
        '您确定要注销账号吗？此操作不可逆，所有数据将被永久删除',
        '警告',
        {
          confirmButtonText: '确认注销',
          cancelButtonText: '取消',
          type: 'warning',
          confirmButtonClass: 'el-button--danger'
        }
    ).then(async () => {
      isCancelLoading.value = true
      try {
        const response = await http.delete('/user/delete', {
          data: {
            password: cancelForm.password,
            reason: cancelForm.reason === "other" ? cancelForm.otherReason : cancelForm.reason
          }
        })
        if (response.code === 200) {
          ElMessage.success("账号注销成功")
          cancelFormRef.value.resetFields()
          // 成功注销后，跳转到登录页
          router.push('/login')
        } else {
          if (response.msg.includes('密码') || response.code === 4001) {
            ElMessage.error("密码错误")
          } else {
            ElMessage.error("账号注销失败" + response.msg)
          }
          isCancelLoading.value = false
        }
      } catch (error) {
        console.error('注销请求失败:', error)
        ElMessage.error("账号注销失败，请重试")
      } finally {
        // 重要：无论成功或失败，都要重置加载状态
        isCancelLoading.value = false
      }
    }).catch(() => {
      // 用户取消操作
      isCancelLoading.value = false
    })
  } catch (error) {
    console.error('表单验证失败:', error)
    // 表单验证失败时也要确保加载状态为 false
    isCancelLoading.value = false
    return false
  }
}

// 导航栏相关功能
const handleCommand = (command) => {
  switch (command) {
    case 'logout':
      handleLogout()
      break
  }
}

// 返回首页
const goHome = () => {
  router.push('/')
}

const handleGoToTab = (tabName) => {
  activeTab.value = tabName; // 切换到对应标签（如个人信息、账号安全）
  router.push('/userInfo'); // 跳回 /userInfo 根路径，显示原有内容
};
// 退出登录处理
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 清除登录状态
    sessionStorage.removeItem('isLogged')
    sessionStorage.removeItem('token')
    ElMessage.success('退出登录成功')
    // 跳转到登录页
    router.push('/login')
  }).catch(() => {
    // 用户取消操作
  })
}

// 切换账户安全标签页
const switchSecurityTab = (tabName) => {
  securityTab.value = tabName
  if (tabName === 'email') {
    emailForm.currentEmail = userInfo.email
    emailForm.verifyCode = ''
  }
}
</script>

<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <header class="top-navbar">
      <div class="navbar-content">
        <div class="navbar-left">
          <h1 class="logo">个人中心</h1>
        </div>
        <div class="navbar-right">

          <!-- 返回首页按钮 -->
          <el-button
              :icon="ArrowLeft"
              class="home-btn"
              @click="goHome"
          >
            返回首页
          </el-button>
          <!-- 新增：签到按钮 -->
          <el-button
              v-if="activeTab !== 'checkIn'"
              :icon="Calendar"
              :loading="checkInStatus.checkInLoading"
              :type="checkInStatus.hasCheckedIn ? 'success' : 'primary'"
              class="checkin-btn"
              @click="handleCheckIn"
          >
            {{ checkInStatus.hasCheckedIn ? '今日已签到' : '每日签到' }}
            <template v-if="checkInStatus.continuousDays > 0">
              <span class="checkin-days">(已连续{{ checkInStatus.continuousDays }}天)</span>
            </template>
          </el-button>
          <!-- 用户信息下拉菜单 -->
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-avatar :size="32" :src="userInfo.avatar" class="user-avatar"/>
              <span class="user-name">{{ userInfo.username || '用户' }}</span>
              <el-icon class="el-icon--right">
                <arrow-down/>
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </header>

    <div class="main-layout">
      <!-- 左侧固定菜单 -->
      <aside class="sidebar">
        <nav class="menu-list">
          <div
              :class="{ active: isMenuActive('profile') }"
              class="menu-item"
              @click="handleGoToTab('profile')"
          >
            <span>个人信息</span>
          </div>
          <div
              :class="{ active: isMenuActive('security') }"
              class="menu-item"
              @click="handleGoToTab('security')"
          >
            <span>账号安全</span>
          </div>
          <!-- 签到记录菜单 -->
          <div :class="{ active: isMenuActive('checkIn') }" class="menu-item" @click="handleGoToTab('checkIn')">
            <span>签到记录</span>
          </div>
          <!--          <div-->
          <!--              :class="{ active: isMenuActive('collections') }"-->
          <!--              class="menu-item"-->
          <!--              @click="handleGoToTab('collections')"-->
          <!--          >-->
          <!--            <span>我的收藏</span>-->
          <!--          </div>-->
          <div
              :class="{ active: isMenuActive('messages') }"
              class="menu-item"
              @click="handleGoToTab('messages')"
          >
            <span>消息中心</span>
          </div>
          <div
              :class="{ active: isMenuActive('fans') }"
              class="menu-item"
              @click="handleGoToTab('fans')"
          >
            <span>粉丝管理</span>
          </div>
          <div
              :class="{ active: isMenuActive('points') }"
              class="menu-item"
              @click="$router.push('/userInfo/points')"
          >
            <span>我的积分</span>
          </div>
          <div
              :class="{ active: isMenuActive('level') }"
              class="menu-item"
              @click="$router.push('/userInfo/level')"
          >
            <span>等级信息</span>
          </div>
          <div
              :class="{ active: isMenuActive('mall')}"
              class="menu-item"
              @click="$router.push('/userInfo/mall')"
          >
            <span>积分商城</span>
          </div>
        </nav>
      </aside>

      <!-- 右侧内容区域 -->
      <main class="main-content">
        <template v-if="$route.path === '/userInfo'">
          <!-- 个人信息 -->
          <div v-if="activeTab === 'profile'">
            <el-card class="settings-card">
              <!-- 个人信息分为左右两栏布局 -->
              <div class="profile-container">
                <!-- 左侧：头像区域 -->
                <div class="profile-left">
                  <div class="avatar-upload-section">
                    <!--头像放大-->
                    <el-image-viewer
                        v-if="showAvatarViewer"
                        :url-list="[userInfo.avatar]"
                        @close="showAvatarViewer = false"/>
                    <el-upload
                        :before-upload="beforeAvatarUpload"
                        :http-request="handleAvatarUpload"
                        :show-file-list="false"
                        action="#"
                        class="avatar-uploader"
                    >
                      <!--点击头像放大显示-->
                      <div @click="handleAvatarClick">
                        <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar"/>
                        <el-icon v-else class="avatar-uploader-icon">
                          <UserFilled/>
                        </el-icon>
                      </div>
                    </el-upload>
                    <!--上传头像按钮-->
                    <el-button class="change-avatar-btn" size="small" type="primary"
                               @click="triggerAvatarUpload">更换头像
                    </el-button>
                    <p class="avatar-hint">(点击上传头像，支持JPG、PNG格式，大小不超过2MB)</p>
                  </div>
                </div>

                <!-- 右侧：表单内容和按钮 -->
                <div class="profile-right">
                  <el-form
                      ref="profileFormRef"
                      :model="userInfo"
                      :rules="profileRules"
                      class="form-fields"
                      label-width="120px"
                  >
                    <!-- 用户ID（只读） -->
                    <el-form-item label="用户ID">
                      <el-input v-model="userInfo.userId" disabled placeholder="用户ID"/>
                    </el-form-item>

                    <el-form-item label="昵称" prop="username">
                      <el-input v-model="userInfo.username" maxlength="20" placeholder="请输入昵称"/>
                    </el-form-item>

                    <!-- 性别 -->
                    <el-form-item label="性别" prop="gender">
                      <el-radio-group v-model="userInfo.gender">
                        <el-radio label="male">男</el-radio>
                        <el-radio label="female">女</el-radio>
                        <el-radio label="secret">保密</el-radio>
                      </el-radio-group>
                    </el-form-item>

                    <el-form-item label="简介" prop="briefly">
                      <el-input
                          v-model="userInfo.briefly"
                          :rows="4"
                          maxlength="100"
                          placeholder="请输入个人简介"
                          type="textarea"
                      />
                    </el-form-item>

                    <el-form-item>
                      <el-button type="primary" @click="saveProfile">保存修改</el-button>
                      <el-button type="danger" @click="resetProfileForm">取消</el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </div>
            </el-card>
          </div>

          <!-- 账户安全 -->
          <div v-if="activeTab === 'security'">
            <el-card class="settings-card">
              <!-- 账户安全标签页 -->
              <div class="security-tabs">
                <div
                    :class="{ active: securityTab === 'password' }"
                    class="security-tab"
                    @click="switchSecurityTab('password')"
                >
                  <el-icon>
                    <UserFilled/>
                  </el-icon>
                  <span>修改密码</span>
                </div>
                <div
                    :class="{ active: securityTab === 'email' }"
                    class="security-tab"
                    @click="switchSecurityTab('email')"
                >
                  <el-icon>
                    <Message/>
                  </el-icon>
                  <span>绑定邮箱</span>
                </div>
                <div
                    :class="{ active: securityTab === 'cancel' }"
                    class="security-tab"
                    @click="switchSecurityTab('cancel')"
                >
                  <el-icon>
                    <User/>
                  </el-icon>
                  <span>注销账号</span>
                </div>
              </div>

              <!-- 修改密码 -->
              <div v-if="securityTab === 'password'" class="security-content">
                <el-form
                    ref="passwordFormRef"
                    :model="passwordForm"
                    :rules="passwordRules"
                    class="security-form"
                    label-width="120px"
                >
                  <el-form-item label="原密码" prop="oldPassword">
                    <el-input v-model="passwordForm.oldPassword" placeholder="请输入原密码" show-password
                              type="password"/>
                  </el-form-item>
                  <el-form-item label="新密码" prop="newPassword">
                    <el-input v-model="passwordForm.newPassword" placeholder="请输入新密码" show-password
                              type="password"/>
                  </el-form-item>
                  <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input v-model="passwordForm.confirmPassword" placeholder="请确认新密码" show-password
                              type="password"/>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="changePassword">确认修改</el-button>
                  </el-form-item>
                </el-form>
              </div>

              <!-- 绑定邮箱 -->
              <div v-if="securityTab === 'email'" class="security-content">
                <el-form
                    ref="emailFormRef"
                    :model="emailForm"
                    :rules="emailRules"
                    class="security-form"
                    label-width="120px"
                >
                  <el-form-item label="当前邮箱" prop="currentEmail">
                    <el-input v-model="emailForm.currentEmail" readonly/>
                  </el-form-item>
                  <el-form-item label="新邮箱" prop="newEmail">
                    <el-input v-model="emailForm.newEmail" placeholder="请输入新邮箱"/>
                  </el-form-item>
                  <el-form-item label="验证码" prop="verifyCode">
                    <el-row :gutter="10">
                      <el-col :span="14">
                        <el-input v-model="emailForm.verifyCode" maxlength="6" placeholder="请输入验证码"/>
                      </el-col>
                      <el-col :span="10">
                        <el-button
                            :disabled="isSendingCode"
                            type="default"
                            @click="sendVerifyCode"
                        >
                          {{ isSendingCode ? `${countdown}秒后重新发送` : '发送验证码' }}
                        </el-button>
                      </el-col>
                    </el-row>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="changeEmail">确认修改</el-button>
                  </el-form-item>
                </el-form>
              </div>

              <!-- 注销账号 -->
              <div v-if="securityTab === 'cancel'" class="security-content">
                <div class="cancel-warning">
                  <el-alert
                      :closable="false"
                      description="账号注销后，所有数据将被永久删除且无法恢复，请谨慎操作！"
                      show-icon
                      title="警告"
                      type="warning"
                  />
                </div>
                <el-form
                    ref="cancelFormRef"
                    :model="cancelForm"
                    :rules="cancelRules"
                    class="security-form"
                    label-width="120px"
                >
                  <el-form-item label="当前密码" prop="password">
                    <el-input v-model="cancelForm.password" placeholder="请输入当前密码确认" show-password
                              type="password"/>
                  </el-form-item>
                  <el-form-item label="注销原因" prop="reason">
                    <el-select v-model="cancelForm.reason" placeholder="请选择注销原因" style="width: 100%">
                      <el-option label="不再使用该账号" value="no_longer_use"/>
                      <el-option label="隐私担忧" value="privacy_concerns"/>
                      <el-option label="账号安全问题" value="security_issues"/>
                      <el-option label="其他原因" value="other"/>
                    </el-select>
                  </el-form-item>

                  <!-- 其他原因输入框 -->
                  <el-form-item
                      v-if="cancelForm.reason === 'other'"
                      key="other-reason"
                      label="具体原因"
                      prop="otherReason"
                  >
                    <el-input
                        v-model="cancelForm.otherReason"
                        :rows="3"
                        maxlength="200"
                        placeholder="请详细说明注销账号的具体原因"
                        show-word-limit
                        type="textarea"
                    />
                  </el-form-item>

                  <el-form-item>
                    <el-button
                        :loading="isCancelLoading"
                        type="danger"
                        @click="confirmCancelAccount"
                    >
                      {{ isCancelLoading ? '注销中...' : '确认注销账号' }}
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-card>
          </div>
          <!-- 新增：签到记录页面 -->
          <div v-if="activeTab === 'checkIn'">
            <el-card class="settings-card">
              <!-- 标题+签到按钮+奖励提示 -->
              <div class="checkin-header">
                <h2>我的签到记录</h2>
                <div class="checkin-header-actions">
                  <!-- 签到按钮 -->
                  <el-button
                      :loading="checkInStatus.checkInLoading"
                      :type="checkInStatus.hasCheckedIn ? 'success' : 'primary'"
                      icon="Calendar"
                      @click="handleCheckIn"
                  >
                    {{ checkInStatus.hasCheckedIn ? '今日已签到' : '立即签到' }}
                  </el-button>
                  <!-- 奖励提示（有奖励时显示） -->
                  <el-tag v-if="checkInStatus.rewardTip" style="margin-left: 12px;" type="info">
                    {{ checkInStatus.rewardTip }}
                  </el-tag>
                </div>
              </div>

              <!-- 签到统计卡片 -->
              <div class="checkin-stats">
                <el-card class="stat-card" shadow="hover">
                  <div class="stat-icon">
                    <el-icon style="color: #409eff;">
                      <Calendar/>
                    </el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-label">当前连续签到</div>
                    <div class="stat-value">{{ checkInStatus.continuousDays }} 天</div>
                    <div v-if="checkInStatus.continuousDays >= 3" class="stat-desc">
                      再接再厉，坚持更久吧！
                    </div>
                  </div>
                </el-card>
                <el-card class="stat-card" shadow="hover">
                  <div class="stat-icon">
                    <el-icon style="color: #67c23a;">#</el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-label">本月累计签到</div>
                    <div class="stat-value">{{ checkInStatus.monthCheckCount }} 天</div>
                    <div class="stat-desc">
                      本月已签到{{
                        Math.round((checkInStatus.monthCheckCount / new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate()) * 100)
                      }}%
                    </div>
                  </div>
                </el-card>
                <el-card class="stat-card" shadow="hover">
                  <div class="stat-icon">
                    <el-icon style="color: #e6a23c;">★</el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-label">总签到次数</div>
                    <div class="stat-value">{{ checkInStatus.totalCheckCount }} 次</div>
                    <div class="stat-desc">
                      {{ checkInStatus.totalCheckCount >= 100 ? '签到达人' : '继续加油' }}
                    </div>
                  </div>
                </el-card>
              </div>
            </el-card>
          </div>

          <!--我的收藏-->
          <div v-if="activeTab === 'collections'">
            <el-card class="settings-card">
              <div class="empty-state">
                <el-icon class="empty-icon">
                  <Collection/>
                </el-icon>
                <p>暂无收藏内容</p>
              </div>
            </el-card>
          </div>

          <!--消息中心-->
          <div v-if="activeTab === 'messages'">
            <el-card class="settings-card">
              <div class="messages-header">
                <h2>消息中心</h2>
                <div class="messages-actions">
                  <el-button
                      :disabled="selectedMessages.length === 0"
                      @click="batchMarkAsRead"
                  >
                    标记已读
                  </el-button>
                  <el-button
                      :disabled="selectedMessages.length === 0"
                      type="danger"
                      @click="batchDeleteMessages"
                  >
                    批量删除
                  </el-button>
                  <el-button
                      :loading="messageLoading"
                      type="primary"
                      @click="refreshMessages"
                  >
                    刷新
                  </el-button>
                </div>
              </div>

              <!-- 消息列表 -->
              <div v-if="messages.length > 0" class="messages-list">
                <el-table
                    v-loading="messageLoading"
                    :data="messages"
                    style="width: 100%"
                    @selection-change="handleMessageSelectionChange"
                >
                  <el-table-column type="selection" width="55"/>
                  <el-table-column label="消息内容" min-width="300">
                    <template #default="{ row }">
                      <div class="message-content">
                        <div :class="{ 'unread': row.isRead === 0 }" class="message-title">
                          {{ row.title }}
                        </div>
                        <div class="message-desc">{{ row.content }}</div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="时间" width="180">
                    <template #default="{ row }">
                      {{ formatTime(row.createTime) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="状态" width="100">
                    <template #default="{ row }">
                      <el-tag :type="row.isRead === 1 ? 'success' : 'warning'">
                        {{ row.isRead === 1 ? '已读' : '未读' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120">
                    <template #default="{ row }">
                      <el-button
                          v-if="row.isRead === 0"
                          link
                          type="primary"
                          @click="markAsRead(row.id)"
                      >
                        标记已读
                      </el-button>
                      <el-button
                          link
                          type="danger"
                          @click="deleteMessage(row.id)"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="pagination-container">
                  <el-pagination
                      v-model:current-page="messagePage.current"
                      v-model:page-size="messagePage.size"
                      :page-sizes="[10, 20, 50]"
                      :total="messagePage.total"
                      layout="total, sizes, prev, pager, next, jumper"
                      @size-change="handleMessageSizeChange"
                      @current-change="handleMessageCurrentChange"
                  />
                </div>
              </div>

              <!-- 空状态 -->
              <div v-else class="empty-state">
                <el-icon class="empty-icon">
                  <Message/>
                </el-icon>
                <p>暂无消息</p>
              </div>
            </el-card>
          </div>

          <!--粉丝管理-->
          <div v-if="activeTab === 'fans'">
            <el-card class="settings-card">
              <!-- 粉丝数据统计 -->
              <div class="fans-stats">
                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-card shadow="hover">
                      <div class="stat-item">
                        <div class="stat-label">粉丝总数</div>
                        <div class="stat-value">{{ fansStatistics.totalFans || 0 }}</div>
                      </div>
                    </el-card>
                  </el-col>
                  <el-col :span="12">
                    <el-card shadow="hover">
                      <div class="stat-item">
                        <div class="stat-label">关注总数</div>
                        <div class="stat-value">{{ fansStatistics.totalFollow || 0 }}</div>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>
              </div>

              <!-- 粉丝管理标签页 -->
              <el-tabs v-model="fansActiveTab" class="fans-tabs" @tab-click="handleTabChange">
                <!-- 粉丝列表 -->
                <el-tab-pane label="我的粉丝" name="fansList">
                  <!-- 搜索框 - 只在粉丝列表标签页显示 -->
                  <div class="search-container">
                    <el-input
                        v-model="searchKeyword"
                        clearable
                        placeholder="搜索用户名"
                        style="width: 300px; margin-right: 10px;"
                        @clear="handleSearchClear"
                        @keyup.enter="handleSearch"
                    >
                      <template #append>
                        <el-button :icon="Search" @click="handleSearch"/>
                      </template>
                    </el-input>
                    <el-button @click="handleReset">重置</el-button>
                  </div>

                  <div class="fans-list">
                    <div v-if="fansList.length === 0" class="empty-state">
                      <el-icon class="empty-icon">
                        <User/>
                      </el-icon>
                      <p>{{ searchKeyword ? '未找到匹配的粉丝' : '暂无粉丝' }}</p>
                    </div>
                    <div v-else>
                      <div v-for="fans in fansList" :key="fans.fansId" class="fans-item">
                        <div class="fans-info" @click="router.push(`/MyHomePage?userId=${fans.fansId}`)">
                          <el-avatar :size="40" :src="fans.avatar" class="fans-avatar"/>
                          <div class="fans-details">
                            <div class="fans-name">{{ fans.username }}</div>
                            <div class="fans-time">关注时间: {{ formatTime(fans.attentionTime) }}</div>
                          </div>
                        </div>
                        <div class="fans-actions">
                          <el-button
                              :type="fans.isFollowing ? 'primary' : 'default'"
                              size="small"
                              @click="toggleFollow(fans.fansId)"
                          >
                            {{ fans.isFollowing ? '已关注' : '回关' }}
                          </el-button>
                        </div>
                      </div>

                      <!-- 分页 -->
                      <div class="pagination-container">
                        <el-pagination
                            v-model:current-page="fansPage.current"
                            v-model:page-size="fansPage.size"
                            :page-sizes="[10, 20, 50]"
                            :total="fansPage.total"
                            layout="total, sizes, prev, pager, next, jumper"
                            @size-change="handleFansSizeChange"
                            @current-change="handleFansCurrentChange"
                        />
                      </div>
                    </div>
                  </div>
                </el-tab-pane>

                <!-- 关注列表 -->
                <el-tab-pane label="我的关注" name="followingList">
                  <!-- 搜索框 - 只在关注列表标签页显示 -->
                  <div class="search-container">
                    <el-input
                        v-model="searchKeyword"
                        clearable
                        placeholder="搜索用户名"
                        style="width: 300px; margin-right: 10px;"
                        @clear="handleSearchClear"
                        @keyup.enter="handleSearch"
                    >
                      <template #append>
                        <el-button :icon="Search" @click="handleSearch"/>
                      </template>
                    </el-input>
                    <el-button @click="handleReset">重置</el-button>
                  </div>

                  <div class="following-list">
                    <div v-if="followingList.length === 0" class="empty-state">
                      <el-icon class="empty-icon">
                        <User/>
                      </el-icon>
                      <p>{{ searchKeyword ? '未找到匹配的关注' : '暂无关注' }}</p>
                    </div>
                    <div v-else>
                      <div v-for="following in followingList" :key="following.id" class="following-item">
                        <div class="following-info">
                          <el-avatar :size="40" :src="following.avatar" class="following-avatar"/>
                          <div class="following-details">
                            <div class="following-name">{{ following.username }}</div>
                            <div class="following-time">关注时间: {{ formatTime(following.attentionTime) }}</div>
                          </div>
                        </div>
                        <div class="following-actions">
                          <el-button
                              size="small"
                              type="danger"
                              @click="toggleFollow(following.authorId)"
                          >
                            取消关注
                          </el-button>
                        </div>
                      </div>

                      <!-- 分页 -->
                      <div class="pagination-container">
                        <el-pagination
                            v-model:current-page="followingPage.current"
                            v-model:page-size="followingPage.size"
                            :page-sizes="[10, 20, 50]"
                            :total="followingPage.total"
                            layout="total, sizes, prev, pager, next, jumper"
                            @size-change="handleFollowingSizeChange"
                            @current-change="handleFollowingCurrentChange"
                        />
                      </div>
                    </div>
                  </div>
                </el-tab-pane>

                <!-- 粉丝数据分析 -->
                <el-tab-pane label="数据分析" name="fansAnalysis">
                  <div class="fans-analysis">
                    <el-row :gutter="16">
                      <el-col :span="12">
                        <el-card header="粉丝增长趋势">
                          <div class="chart-placeholder">
                            <div v-if="fansAnalysisData.growthTrend && fansAnalysisData.growthTrend.length > 0">
                              <div v-for="item in fansAnalysisData.growthTrend" :key="item.date" class="trend-item">
                                <span class="trend-date">{{ item.date }}</span>
                                <span class="trend-count">新增: {{ item.count }} 人</span>
                              </div>
                            </div>
                            <div v-else>
                              <p>暂无数据</p>
                            </div>
                            <!-- 这里可以接入 ECharts 图表 -->
                          </div>
                        </el-card>
                      </el-col>
                      <el-col :span="12">
                        <el-card header="粉丝数据概览">
                          <div class="analysis-overview">
                            <div class="analysis-item">
                              <span class="label">粉丝总数:</span>
                              <span class="value">{{ fansStatistics.totalFans || 0 }}</span>
                            </div>
                            <div class="analysis-item">
                              <span class="label">关注总数:</span>
                              <span class="value">{{ fansStatistics.totalFollow || 0 }}</span>
                            </div>
                            <div class="analysis-item">
                              <span class="label">近7天新增:</span>
                              <span class="value">
                              {{
                                  fansAnalysisData.growthTrend ? fansAnalysisData.growthTrend.reduce((sum, item) => sum + item.count, 0) : 0
                                }}
                            </span>
                            </div>
                          </div>
                        </el-card>
                      </el-col>
                    </el-row>

                    <!-- 更多分析数据 -->
                    <el-row :gutter="16" style="margin-top: 16px;">
                      <el-col :span="12">
                        <el-card header="互动统计">
                          <div class="chart-placeholder">
                            <p>互动统计图表（开发中）</p>
                          </div>
                        </el-card>
                      </el-col>
                      <el-col :span="12">
                        <el-card header="粉丝活跃度">
                          <div class="chart-placeholder">
                            <p>粉丝活跃度图表（开发中）</p>
                          </div>
                        </el-card>
                      </el-col>
                    </el-row>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </el-card>
          </div>
        </template>
        <template v-else>
          <router-view/>
        </template>
      </main>
    </div>
  </div>
</template>

<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.top-navbar {
  height: 60px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.navbar-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  padding: 0 20px;
  max-width: 100%;
}

.logo {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #1890ff;
}

.navbar-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.home-btn {
  display: flex;
  align-items: center;
  gap: 4px;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f7fa;
}

.user-avatar {
  margin-right: 8px;
}

.user-name {
  margin-right: 4px;
  font-size: 14px;
}


.main-layout {
  display: flex;
  flex: 1;
  margin-top: 60px;
}


.sidebar {
  width: 200px;
  background-color: #fff;
  height: calc(100vh - 60px);
  position: fixed;
  left: 0;
  top: 60px;
  overflow-y: auto;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
}

.menu-list {
  padding: 10px 0;
}

.menu-item {
  padding: 12px 20px;
  cursor: pointer;
  transition: background-color 0.3s;
  border-radius: 4px;
  margin: 0 10px;
}

.menu-item:hover {
  background-color: #f5f7fa;
}

.menu-item.active {
  background-color: #e6f7ff;
  color: #1890ff;
  font-weight: 500;
}


.main-content {
  flex: 1;
  margin-left: 200px;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}


.security-tabs {
  display: flex;
  border-bottom: 1px solid #e6e6e6;
  margin-bottom: 20px;
}

.security-tab {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
  color: #666;
}

.security-tab:hover {
  color: #1890ff;
  background-color: #f5f7fa;
}

.security-tab.active {
  color: #1890ff;
  border-bottom-color: #1890ff;
  background-color: #f0f8ff;
}

.security-tab .el-icon {
  font-size: 16px;
}

.security-content {
  padding: 0 20px;
}

.cancel-warning {
  margin-bottom: 20px;
}

.security-form {
  max-width: 500px;
}

.profile-container {
  display: flex;
  gap: 40px;
  padding: 20px;
}

/* 左侧头像区域 */
.profile-left {
  flex: 0 0 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20px;
}

/* 右侧表单内容 */
.profile-right {
  flex: 1;
  min-width: 0;
}

.avatar {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-hint {
  margin-top: 10px;
  color: #666;
  font-size: 14px;
  text-align: center;
}


.change-avatar-btn {
  margin-top: 15px;
  width: 150px;
}


.avatar-uploader {
  cursor: pointer;
}

.field-hint {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
}

/* 性别选择器样式 */
.el-radio-group {
  display: flex;
  gap: 20px;
}

/* 签到头部 */
.checkin-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.checkin-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.checkin-header-actions {
  display: flex;
  align-items: center;
}

/* 统计卡片 */
.checkin-stats {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  flex-wrap: wrap;
}

.stat-card {
  flex: 1 1 200px;
  display: flex;
  padding: 16px;
}

.stat-icon {
  font-size: 24px;
  margin-right: 12px;
}

.stat-info {
  flex: 1;
}

.stat-label {
  color: #606266;
  font-size: 14px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  margin: 4px 0;
}

.stat-desc {
  color: #909399;
  font-size: 12px;
}


/* 签到规则说明 */
.checkin-rules {
  margin-top: 24px;
}

/* 粉丝管理样式 */
.fans-stats {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #1890ff;
}

.fans-tabs {
  margin-top: 20px;
}

/* 搜索框样式 */
.search-container {
  display: flex;
  align-items: center;
  margin: 20px 0;
  padding: 0 10px;
}

.fans-item, .following-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s;
}

.fans-item:hover, .following-item:hover {
  background-color: #f5f7fa;
}

.fans-info, .following-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.fans-avatar, .following-avatar {
  margin-right: 12px;
}

.fans-details, .following-details {
  flex: 1;
}

.fans-name, .following-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.fans-time, .following-time {
  font-size: 12px;
  color: #909399;
}

.fans-actions, .following-actions {
  margin-left: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.fans-analysis {
  padding: 10px 0;
}

.chart-placeholder {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #909399;
}


/* 粉丝分析样式 */
.trend-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.trend-item:last-child {
  border-bottom: none;
}

.trend-date {
  color: #606266;
}

.trend-count {
  color: #1890ff;
  font-weight: 500;
}

.analysis-overview {
  padding: 10px 0;
}

.analysis-item {
  display: flex;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.analysis-item:last-child {
  border-bottom: none;
}

.analysis-item .label {
  color: #606266;
}

.analysis-item .value {
  color: #1890ff;
  font-weight: 600;
}

/* 图表占位符样式优化 */
.chart-placeholder {
  height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #909399;
  padding: 20px;
}

/* 消息中心样式 */
.messages-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.messages-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.messages-actions {
  display: flex;
  gap: 10px;
}

.messages-list {
  margin-top: 20px;
}

.message-content {
  padding: 8px 0;
}

.message-title {
  font-weight: 500;
  margin-bottom: 4px;
  font-size: 14px;
}

.message-title.unread {
  color: #1890ff;
  font-weight: 600;
}

.message-desc {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

/* 空状态样式优化 */
.empty-state {
  text-align: center;
  padding: 60px 0;
  color: #909399;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
}
</style>